<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card">
            <el-form :model="queryParams" :inline="true">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="时间范围" style="width: 100%">
                            <el-date-picker v-model="timeRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="区域名称" style="width: 100%">
                            <el-input v-model="queryParams.areaName" placeholder="请输入区域名称" clearable
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警状态" style="width: 100%">
                            <el-select v-model="queryParams.alarmStatus" placeholder="请选择报警状态" clearable
                                style="width: 100%">
                                <el-option label="全部" value="" />
                                <el-option label="关闭" :value="0" />
                                <el-option label="开启" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="报警类型" style="width: 100%">
                            <el-select v-model="queryParams.alarmType" placeholder="请选择报警类型" clearable
                                style="width: 100%">
                                <el-option v-for="value in alarmTypeOptions" :key="value.dictValue"
                                    :label="value.dictLabel" :value="value.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6" class="mt-2">
                        <el-form-item label="报警等级" style="width: 100%">
                            <el-select v-model="queryParams.alarmLevel" placeholder="请选择报警等级" clearable
                                style="width: 100%">
                                <el-option v-for="value in alarmLevelOptions" :key="value.dictValue"
                                    :label="value.dictLabel" :value="value.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="mt-2">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <!-- 数据表格区域 -->
        <el-card class="mt-2">
            <div class="flex-between mb-2">
                <div>
                    <el-button type="primary" @click="handleBatchEnable" :disabled="!selectedRows.length"
                        icon="CircleCheck">
                        批量开启
                    </el-button>
                    <el-button type="danger" @click="handleBatchDisable" :disabled="!selectedRows.length"
                        icon="CircleClose">
                        批量关闭
                    </el-button>
                </div>
                <!-- <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="fetchList"
                    :columns="columns" /> -->
            </div>

            <el-table :data="alarmList" border v-loading="loading" @selection-change="handleSelectionChange"
                class="mt-2">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="areaName" label="区域名称" align="center" v-if="columns[0].visible" />
                <el-table-column prop="confirmUser" label="确认人" align="center" v-if="columns[0].visible" />

                <el-table-column label="报警状态" align="center" v-if="columns[1].visible">
                    <template #default="{ row }">
                        <el-tag :type="row.alarmStatus === 1 ? 'danger' : 'info'">
                            {{ row.alarmStatus === 1 ? '开启' : '关闭' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="报警类型" align="center">
                    <template #default="{ row }">
                        {{ getName(alarmTypeOptions,row.alarmType,'dictValue','dictLabel') }}
                    </template>
                </el-table-column>
                <el-table-column label="报警等级" align="center">
                    <template #default="{ row }">
                        {{ getName(alarmLevelOptions,row.alarmLevel,'dictLabel','dictValue') }}
                    </template>
                </el-table-column>
                <el-table-column prop="triggerCount" label="触发次数" align="center" width="120"
                    v-if="columns[2].visible" />
                <el-table-column prop="monitoringParameter" label="监测参数" align="center" v-if="columns[3].visible" />
                <el-table-column label="阈值范围" align="center" width="200" v-if="columns[4].visible">
                    <template #default="{ row }">
                        {{ row.lowerThreshold }} ~ {{ row.upperThreshold }}
                    </template>
                </el-table-column>
                <el-table-column prop="alarmTime" label="报警时间" align="center" width="180" v-if="columns[5].visible" />
                <el-table-column label="报警等级" align="center" width="120" v-if="columns[6].visible">
                    <template #default="{ row }">
                        <el-tag :type="getAlarmLevelTagType(row.alarmLevel)">
                            {{ getAlarmLevelLabel(row.alarmLevel) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="报警等级" align="center" width="120" v-if="columns[6].visible">
                    <template #default="{ row }">
                        <el-tag :type="getAlarmLevelTagType(row.alarmLevel)">
                            {{ getAlarmLevelLabel(row.alarmLevel) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right" v-if="columns[7].visible">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleDetail(row)">详情</el-button>
                        <el-button size="small" :type="row.alarmStatus === 1 ? 'danger' : 'success'"
                            @click="toggleAlarmStatus(row)">
                            {{ row.alarmStatus === 1 ? '关闭' : '开启' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialog.visible" :title="`区域报警详情 - ${detailData.areaName}`" width="800px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="区域名称">{{ detailData.areaName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警状态">
                    <el-tag :type="detailData.alarmStatus === 1 ? 'danger' : 'info'">
                        {{ detailData.alarmStatus === 1 ? '开启' : '关闭' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="触发次数">{{ detailData.triggerCount || '0' }}</el-descriptions-item>
                <el-descriptions-item label="监测参数">{{ detailData.monitoringParameter || '-' }}</el-descriptions-item>
                <el-descriptions-item label="阈值范围">
                    {{ detailData.lowerThreshold || '0' }} ~ {{ detailData.upperThreshold || '0' }}
                </el-descriptions-item>
                <el-descriptions-item label="触发条件">{{ detailData.triggerCondition || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警时间">{{ detailData.alarmTime || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警类型">{{ detailData.alarmType || '-' }}</el-descriptions-item>
                <el-descriptions-item label="报警等级">
                    <el-tag :type="getAlarmLevelTagType(detailData.alarmLevel)">
                        {{ getAlarmLevelLabel(detailData.alarmLevel) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建人">{{ detailData.creator || '-' }}</el-descriptions-item>
                <el-descriptions-item label="确认人">{{ detailData.confirmUser || '-' }}</el-descriptions-item>
                <el-descriptions-item label="确认时间">{{ detailData.confirmTime || '-' }}</el-descriptions-item>
            </el-descriptions>
            <el-table v-if="detailData.messageRecord" :data="detailData.messageRecord" border class="mt-2">
                <el-table-column label="接收人姓名或组名" prop="targetName" align="center">
                </el-table-column>
                 <el-table-column label="状态" prop="status" align="center">
                    <template #default="{ row }">
                        <el-tag v-if="row.status == 0" type="info">待发送</el-tag>
                        <el-tag v-if="row.status == 1" type="success">成功</el-tag>
                        <el-tag v-if="row.status == 2" type="danger">失败</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="发送时间" prop="sentAt" align="center">
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
                <el-button type="primary" @click="toggleAlarmStatus(detailData)">
                    {{ detailData.alarmStatus === 1 ? '关闭报警' : '开启报警' }}
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listAreaAlarms, getAreaAlarmDetail, handleAlarmStatus, getAlarmTypeSelect, getAlarmLevelSelect } from '@/api/dispatch/call/callArea'

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    areaName: '',
    alarmStatus: '',
    alarmLevel: '',
    alarmType: ''
})

const timeRange = ref([])
const alarmList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const showSearch = ref(true)

// 详情对话框
const detailDialog = reactive({
    visible: false
})
const detailData = ref({})

// 列显隐配置
const columns = ref([
    { key: 0, label: '区域名称', visible: true },
    { key: 1, label: '报警状态', visible: true },
    { key: 2, label: '触发次数', visible: true },
    { key: 3, label: '监测参数', visible: true },
    { key: 4, label: '阈值范围', visible: true },
    { key: 5, label: '报警时间', visible: true },
    { key: 6, label: '报警等级', visible: true },
    { key: 7, label: '操作', visible: true }
])

// 报警等级
const alarmLevelOptions = ref([]);
// 报警类型
const alarmTypeOptions = ref([]);

// 报警等级映射
const getAlarmLevelLabel = (level) => {
    const map = { 1: '一般', 2: '警告', 3: '严重' }
    return map[level] || '未知'
}

const getAlarmLevelTagType = (level) => {
    const map = { 1: 'info', 2: 'warning', 3: 'danger' }
    return map[level] || 'info'
}

// 获取报警列表
const fetchList = async () => {
    try {
        loading.value = true
        // 处理时间范围
        if (timeRange.value && timeRange.value.length === 2) {
            queryParams.startTime = timeRange.value[0]
            queryParams.endTime = timeRange.value[1]
        } else {
            queryParams.startTime = ''
            queryParams.endTime = ''
        }
        console.log(queryParams);

        const res = await listAreaAlarms(queryParams)
        alarmList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取报警列表失败:', error)
        ElMessage.error('获取报警列表失败')
    } finally {
        loading.value = false
    }
}

// 查询
const handleQuery = () => {
    queryParams.pageNum = 1
    fetchList()
}

// 重置查询
const resetQuery = () => {
    timeRange.value = []
    queryParams.pageNum = 1
    queryParams.areaName = ''
    queryParams.alarmStatus = ''
    fetchList()
}

// 分页
const handleSizeChange = (size) => {
    queryParams.pageSize = size
    fetchList()
}

const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    fetchList()
}

// 表格选择
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 查看详情
const handleDetail = async (row) => {
    try {
        const res = await getAreaAlarmDetail(row.areaAlarmId)
        detailData.value = res.data || {}
        detailDialog.visible = true
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 切换报警状态
const toggleAlarmStatus = async (row) => {
    const newStatus = row.alarmStatus === 1 ? 0 : 1
    const action = newStatus === 1 ? '开启' : '关闭'

    try {
        await ElMessageBox.confirm(`确认${action}该区域报警吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await handleAlarmStatus({
            areaAlarmId: row.areaAlarmId,
            alarmStatus: newStatus
        })

        ElMessage.success(`${action}成功`)
        fetchList()
        if (detailDialog.visible) {
            detailDialog.visible = false
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error(`${action}失败:`, error)
            ElMessage.error(`${action}失败`)
        }
    }
}

// 批量开启
const handleBatchEnable = async () => {
    try {
        await ElMessageBox.confirm('确认开启选中的报警记录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const promises = selectedRows.value.map(row =>
            handleAlarmStatus({
                areaAlarmId: row.areaAlarmId,
                alarmStatus: 1
            })
        )

        await Promise.all(promises)
        ElMessage.success('批量开启成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量开启失败:', error)
            ElMessage.error('批量开启失败')
        }
    }
}

// 批量关闭
const handleBatchDisable = async () => {
    try {
        await ElMessageBox.confirm('确认关闭选中的报警记录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const promises = selectedRows.value.map(row =>
            handleAlarmStatus({
                areaAlarmId: row.areaAlarmId,
                alarmStatus: 0
            })
        )

        await Promise.all(promises)
        ElMessage.success('批量关闭成功')
        fetchList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量关闭失败:', error)
            ElMessage.error('批量关闭失败')
        }
    }
}

onMounted(async () => {
    const alarmTypeSelect = await getAlarmTypeSelect();
    alarmTypeOptions.value = alarmTypeSelect.data;
    console.log(alarmTypeSelect.value);

    const alarmLevelSelect = await getAlarmLevelSelect();
    alarmLevelOptions.value = alarmLevelSelect.data;
    console.log(alarmLevelSelect.value);

    fetchList()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.mt-2 {
    margin-top: 20px;
}

.flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 表格样式 */
:deep(.el-table) {
    width: 100%;
}

:deep(.el-table__cell) {
    padding: 12px 0;
}

/* 详情页样式 */
:deep(.el-descriptions) {
    margin-top: 20px;
}

:deep(.el-descriptions-item__label) {
    width: 120px;
    font-weight: bold;
}
</style>